#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据库初始化脚本
用于快速设置MySQL数据库环境
"""

import mysql.connector
import os
import sys
from mysql.connector import Error

def read_sql_file(file_path):
    """
    读取SQL文件内容
    
    Args:
        file_path: SQL文件路径
        
    Returns:
        SQL文件内容
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            return file.read()
    except FileNotFoundError:
        print(f"错误: 找不到文件 {file_path}")
        return None
    except Exception as e:
        print(f"错误: 读取文件 {file_path} 时发生错误: {str(e)}")
        return None

def execute_sql_script(cursor, sql_script):
    """
    执行SQL脚本
    
    Args:
        cursor: 数据库游标
        sql_script: SQL脚本内容
    """
    # 分割SQL语句（以分号分隔）
    statements = [stmt.strip() for stmt in sql_script.split(';') if stmt.strip()]
    
    for statement in statements:
        try:
            cursor.execute(statement)
            # 消费结果集以避免"Unread result found"错误
            try:
                cursor.fetchall()
            except:
                pass  # 忽略没有结果集的语句
            print(f"✓ 执行成功: {statement[:50]}...")
        except Error as e:
            print(f"✗ 执行失败: {statement[:50]}...")
            print(f"  错误: {str(e)}")
            return False
    
    return True

def setup_database():
    """
    设置数据库
    """
    print("=== VX Battle 数据库初始化 ===")
    print()
    
    # 获取数据库连接信息
    print("请输入MySQL连接信息:")
    host = input("主机地址 (默认: localhost): ").strip() or "localhost"
    port = input("端口 (默认: 3306): ").strip() or "3306"
    username = input("用户名 (默认: root): ").strip() or "root"
    password = input("密码: ").strip()
    
    try:
        port = int(port)
    except ValueError:
        print("错误: 端口必须是数字")
        return False
    
    print()
    print("连接到MySQL服务器...")
    
    try:
        # 连接到MySQL服务器（不指定数据库）
        connection = mysql.connector.connect(
            host=host,
            port=port,
            user=username,
            password=password
        )
        
        if connection.is_connected():
            print("✓ 成功连接到MySQL服务器")
            
            cursor = connection.cursor()
            
            # 检查数据库是否存在
            cursor.execute("SHOW DATABASES LIKE 'vxbattle'")
            db_exists = cursor.fetchone() is not None
            
            if db_exists:
                print("警告: 数据库 'vxbattle' 已存在")
                choice = input("是否要重新创建数据库？这将删除所有现有数据 (y/N): ").strip().lower()
                
                if choice == 'y':
                    print("删除现有数据库...")
                    cursor.execute("DROP DATABASE vxbattle")
                    print("✓ 数据库已删除")
                else:
                    print("跳过数据库创建")
                    return True
            
            # 读取并执行初始化SQL
            init_sql_path = os.path.join(os.path.dirname(__file__), 'database', 'init_database.sql')
            init_sql = read_sql_file(init_sql_path)
            
            if init_sql is None:
                return False
            
            print("创建数据库...")
            if not execute_sql_script(cursor, init_sql):
                return False
            
            print("✓ 数据库创建成功")
            
            # 连接到新创建的数据库
            connection.database = 'vxbattle'
            
            # 读取并执行建表SQL
            tables_sql_path = os.path.join(os.path.dirname(__file__), 'database', 'create_tables.sql')
            tables_sql = read_sql_file(tables_sql_path)
            
            if tables_sql is None:
                return False
            
            print("创建数据表...")
            if not execute_sql_script(cursor, tables_sql):
                return False
            
            print("✓ 数据表创建成功")
            
            # 提交事务
            connection.commit()
            
            print()
            print("=== 数据库初始化完成 ===")
            print("数据库名称: vxbattle")
            print("包含的表:")
            print("  - accounts (账号表)")
            print("  - characters (角色表)")
            print("  - idle_locations (挂机地点表)")
            print("  - idle_records (挂机记录表)")
            print("  - battles (战斗表)")
            print("  - battle_participants (战斗参与者表)")
            print("  - system_config (系统配置表)")
            print()
            print("现在可以运行游戏了！")
            print("使用命令: python src/main_mysql_gui.py")
            
            return True
            
    except Error as e:
        print(f"✗ 数据库错误: {str(e)}")
        return False
    except Exception as e:
        print(f"✗ 发生错误: {str(e)}")
        return False
    finally:
        if 'connection' in locals() and connection.is_connected():
            cursor.close()
            connection.close()
            print("数据库连接已关闭")

def check_requirements():
    """
    检查运行要求
    """
    print("检查运行环境...")
    
    # 检查Python版本
    if sys.version_info < (3, 6):
        print("✗ Python版本过低，需要Python 3.6或更高版本")
        return False
    
    print(f"✓ Python版本: {sys.version}")
    
    # 检查mysql-connector-python
    try:
        import mysql.connector
        print(f"✓ mysql-connector-python 已安装")
    except ImportError:
        print("✗ 缺少mysql-connector-python")
        print("请运行: pip install mysql-connector-python")
        return False
    
    # 检查SQL文件是否存在
    required_files = [
        'database/init_database.sql',
        'database/create_tables.sql'
    ]
    
    for file_path in required_files:
        full_path = os.path.join(os.path.dirname(__file__), file_path)
        if not os.path.exists(full_path):
            print(f"✗ 缺少文件: {file_path}")
            return False
        print(f"✓ 找到文件: {file_path}")
    
    print("✓ 运行环境检查通过")
    print()
    return True

def main():
    """
    主函数
    """
    print("VX Battle 数据库初始化工具")
    print("=" * 40)
    print()
    
    # 检查运行要求
    if not check_requirements():
        print("\n初始化失败，请解决上述问题后重试")
        return
    
    # 设置数据库
    if setup_database():
        print("\n数据库初始化成功！")
    else:
        print("\n数据库初始化失败！")

if __name__ == "__main__":
    main()